/**
* Class Name: iFulfillProductSearchController
* Author: Accenture
* Date: 9-7-2011
* Requirement/Project Name: iFulfill
* Requirement/Project Description: Controller for Product search page.Invoked from 'Add Products' button product group page layout
**/


public class iFulfillProductSearchController
{
    public String productUdac{get;set;}
    public String productFamily{get;set;}
    public String featureCode{get;set;}
    public String selectedStatus {get;set;}
    public string page;    
    public Boolean noSearchResults{get;set;}            
    public Boolean searchResults{get;set;}     
    public Id grpId;    
    public final Integer pageSize {get;set;}
    public Integer pageNo {get;set;}
    private List<productWrapper> selectWrapperList = new List<productWrapper>();
    
     // FI Product wrapper class
    class productWrapper
    {
        public Fulfillment_Products__c prod{get;set;}
        public boolean selectBox{get;set;}
        Public productWrapper(Fulfillment_Products__c P, Boolean checkBox)
        {
            prod = P;
            selectBox = checkBox;
        }
    }
    
    /** Constructor**/
     
    public iFulfillProductSearchController(ApexPages.StandardController controller) 
    {  
        grpId = ApexPages.currentPage().getParameters().get('gid');
        page = '/'+grpId ; 
        noSearchResults = false;
        searchResults = false;  
        pageSize = 20;
        pageNo = 0;

    }
     /** Action associated with cancel button**/
    public pageReference doCancel()
    {
        PageReference pageRef = new PageReference(page);
        return pageRef ;
    }
    /**Group the FI Products based on region,transcation type and status.**/
    public pageReference doSelect()
    {
        List<Fulfillment_Products__c> updateProdList = new List<Fulfillment_Products__c>();
        for(integer i=0 ; i< selectWrapperList .size(); i++)
        {
           // Check if user has selected any row/record.
            if(selectWrapperList [i].selectBox)
            {
                selectWrapperList [i].prod.Fulfillment_Product_Group__c = grpId;
                updateProdList.add(selectWrapperList [i].prod);
            }
        }
        // update the selected Fulfillment_Products
        try
        {
            Update updateProdList;
        }
        catch(DMLException e)
        {
            GeneralConstants.mailAnyExceptionToMe('iFulfillProductSearchController','doSelect',e);
            system.debug('FI Product Update Failed');
        }         
        catch(Exception ex)
        {
            GeneralConstants.mailAnyExceptionToMe('iFulfillProductSearchController','doSelect',ex);
            system.debug('FI Product Update Failed');
        }         
        
        PageReference pageRef = new PageReference(page);
        return pageRef ;
    }
    
     /**Starts the search based in the user input.**/
    public pageReference doSearch()
    {  
        List<Fulfillment_Products__c> products = new List<Fulfillment_Products__c>();
       
        pageNo = 0;
        selectWrapperList .clear();
        
       // Build the query  based on the inputs from the user.
        
        String qString = 'select ID,Region__c, Product_UDAC_Code__c,Product_Descritpion__c,Product_Family__c,Feature__c,Feature_Description__c,Package__c,Status__c,Fulfillment_Product_Group__c from Fulfillment_Products__c where Fulfillment_Product_Group__c = null ';
        if(productUdac != null && productUdac != '') qString = qString + ' and Product_UDAC_Code__c like \'' + productUdac + '%\'';
        if(productFamily != null && productFamily != '') qString = qString + ' and Product_Family__c like \'' + productFamily + '%\'';
        if(featureCode != null && featureCode != '') qString = qString + ' and Feature__c like \'' + featureCode + '%\'';
        if(selectedStatus != null && selectedStatus != '') qString = qString + ' and Status__c like \'' + selectedStatus + '%\'';                        
       
       // Execute the Query
        try
        {         
            products = Database.Query(qString);  
        }
        catch(DmlException e )
        {
            GeneralConstants.mailAnyExceptionToMe('iFulfillProductSearchController','doSearch',e);
         }
        
        // check the query has return any values 
        if(products.size() > 0)
        {
            searchResults = true;
            noSearchResults = false;             
            
            for(Fulfillment_Products__c fiProduct :Products )
            {
                selectWrapperList.add(new ProductWrapper(fiProduct, false));                          
            }                       
        }
        else
        {
             noSearchResults = true;
             searchResults = false;
        }
          
        return null;
    }
   

  /** Check is there any records displayed for next page.**/
  public boolean getHasNext()
  {
        integer total = pageNo * pageSize;
        // Check is there any records need to be dispalyed.
        return total + pageSize < selectWrapperList .size() ?true :false;
       
  }
  
  /**check user is in first page of the pagination* */  
    public boolean getHasPrevious()
    {
        // check user is in first page of the pagination
        return pageNo  == 0 ?false: true;
    }
    
  /**increment the pagno **/
    public void next()
    {
       pageNo++;
       integer total = pageNo * pageSize;
        // Check is there any records need to be dispalyed.
       if(!(total < selectWrapperList .size()))
       {
          pageNo--;
       }
    }
    
  /**decrement the pagno **/
    public void previous ()
    {      
          pageNo--;
          pageNo = Math.max(pageNo,0);
    }
    
  /**Returns the element displayed on the VF page **/
    public list<productWrapper> getSelectedElements()
    {
           integer total = pageNo * pageSize;
           integer maxlimit = Math.min((total + pageSize),selectWrapperList .size());
           
          List<productWrapper> temp = new list<productWrapper>();
          
            for(integer i=total;i<maxlimit;i++)
           {
               temp.add(selectWrapperList .get(i));
           }                   
           return temp;                 
    }
    
    /**Returns the total no of records fetched**/ 
    public integer getTotalNoOfRecord()
    {
        return selectWrapperList .size();
    }  

  /**Return the Status picklist value.**/
    public List<SelectOption> getStatus()
    {
        List<selectOption> options = new List<selectOption>(); 
        options.add(new selectOption('', IfullfillTextConstant.PICKLIST_NONE_TXT)); 
        Schema.DescribeFieldResult rest =   Fulfillment_Products__c.Status__c.getDescribe();
        for(Schema.PickListEntry FinalsPickVal : rest.getPicklistValues())
        {
            options.add(new SelectOption(FinalsPickVal.getValue(),FinalsPickVal.getLabel()));
        }
        return options;
    }    
    
    /** Returns the product Family for the FI ***/
    public List<SelectOption> getProductFamilyName()
    {
        List<selectOption> options = new List<selectOption>(); 
        options.add(new selectOption('', IfullfillTextConstant.PICKLIST_NONE_TXT)); 
        Schema.DescribeFieldResult rest =   Fulfillment_Products__c.Product_Family__c.getDescribe();
        for(Schema.PickListEntry FinalsPickVal : rest.getPicklistValues())
        {
            options.add(new SelectOption(FinalsPickVal.getValue(),FinalsPickVal.getLabel()));
        }
        return options;
    }  
}